<?php
/*  
	[Phpup.Net!] (C)2009-2011 Phpup.net.
	This is NOT a freeware, use is subject to license terms

	$Id: order.class.php 2010-08-24 10:42 $
*/

if(!defined('IN_PHPUP')) {
	exit('Access Denied');
}
class order_controller extends front_controller
{
	function init()
	{
        parent::init();
		$act=$GLOBALS['action'];
		$nologin=array();
		if(!in_array($act,$nologin))
		{
			if($GLOBALS['userinfo']['uid'] == 0)
			{
				sheader(url('user','login'),1,'请先登录');
			}
		}
	}
    //用户出价
    function bid_action(){
      global $cache;
      $gid = $this->post('goods_id',0);
      if($gid == 0){
        $this->bidcms_error('参数为空');
      }
      if($GLOBALS['userinfo']['uid'] == 0){
        $this->bidcms_error(array('datastatus'=>'nologin'),'请登录后操作');
      }
      $uid = $GLOBALS['userinfo']['uid'];
      $userinfo = $this->bidcms_model('user_base')->fields('money,score')->where('uid',$uid)->get_one();
      $goods = $this->bidcms_model('goods_base')
        ->fields('goods_id,nowprice,currentuser,currentuid,lasttime,diffmoney,diffprice,shutuid,limitnumber,islimit,difftime,addtime,isfree,diffscore,starttime,ispassed')
        ->where('goods_id',$gid)
        ->get_one();
      if($goods['starttime'] < time() && $goods['lasttime'] > time() && $goods['ispassed'] == 1){
        $difftime=intval($goods['difftime']>0?$goods['difftime']:10);
        $addtime=intval($goods['addtime']>0?$goods['addtime']:11);
        if(strpos('a,'.$goods['shutuid'].',a',','.$uid.',')>0)
        {
            $this->bidcms_error('对不起，你暂无权限参与此次拍卖');
        }
        $bid_logs = $this->bidcms_model('goods_bidlog')->fields('count,id,money')->where(['uid'=>$uid,'gid'=>$gid])->get_one();
        if($goods['islimit'] && $goods['limitnumber']>0){
          if($bid_logs['count'] >= $goods['limitnumber']){
            $this->bidcms_error('本商品限制出价次数'.$goods['limitnumber']);
          }
        }
        
        $diffprice = $goods['diffprice']; //每拍一下价格上升
        $diffmoney = abs($goods['isfree'] > 0?1:$goods['diffmoney']); //每拍一下用户扣多少钱
        $diffscore = abs($goods['diffscore']); //每拍一下用户增加积分
        
        if($userinfo['money'] < $diffmoney)
        {
          $this->bidcms_error('对不起,余额不足');
        }

        $nowprice=floatval($goods['nowprice']+$diffprice);
        
        if($uid>0 && $goods['currentuid']!=$uid)
        {
            $udata = ['money'=>floatval($userinfo['money']-$diffmoney)];
            if($goods['isfree']<1)
            { 
              $udata['score'] = intval($userinfo['score']+abs($diffscore));
            }
            $rows = $this->bidcms_model('user_base')->where('uid',$uid)->update_data($udata);
            $cache->update('user'.($uid%10).':'.$uid,$udata);
            if($rows > 0)
            {
                if($bid_logs) {
                    $this->bidcms_model('goods_bidlog')->where('id',$bid_logs['id'])->update_data(array(
                    	'money' => $bid_logs['money']+abs($diffmoney),
                        'count'=> $bid_logs['count']+1,
                        'price'=> $nowprice,
                        'updatetime' => time(),
                    ));
                } else {
                    $this->bidcms_model('goods_bidlog')->insert_data(array(
                    	'username' => $GLOBALS['userinfo']['username'],
                        'gid'=> $gid,
                        'uid'=> $uid,
                        'count' => 1,
                        'money' => $diffmoney,
                        'ip' => $GLOBALS['userinfo']['ip'],
                        'updatetime' => time(),
                        'price' => $nowprice,
                        'address' => $GLOBALS['userinfo']['address'],
                        'mobile' => $GLOBALS['userinfo']['mobile'],
                        'usertype' => $GLOBALS['userinfo']['usertype']
                  ));
                 }
                $data = ['currentuser'=>$GLOBALS['userinfo']['username'],'currentuid'=>$uid,'nowprice'=>$nowprice];
                if($goods['lasttime']>=time() && $goods['lasttime']-time()<$difftime) {
                    $data['lasttime'] = intval($goods['lasttime']+$addtime);
                }
                $this->bidcms_model('goods_base')->where('goods_id',$gid)->update_data($data);
                $data['usertype'] = $GLOBALS['userinfo']['usertype'];
                $this->bidcms_model('goods_cache')->where('goods_id',$gid)->update_data($data);
                $data['id'] = $gid;
                $data['lasttime'] = (isset($data['lasttime'])?$data['lasttime']:$goods['lasttime']) - time();
                unset($data['usertype']);
                $this->bidcms_success($data,'出价成功','');
			}
        }
        $this->bidcms_error('不用重复出价');
      }
    }
	//用户下单
	function index_action()
	{
		$goodsid=intval($this->get('goodsid'));
		
		//得到收货地址
		$address_mod=$this->bidcms_model('user_address');
		$address=$address_mod->where(array('uid'=>$GLOBALS['userinfo']['uid']))->get_page();
		if($goodsid)
		{
			$goods_mod=$this->bidcms_model('goods_complete');
			$goods=$goods_mod->where('goods_id',$goodsid)->fields(array('goods_id','putmoney','goods_status','marketprice','nowprice','goods_name','diffmoney','currentuid','yfeemoney'))->get_one();
			
			$order_type=0;
			if($goods)
			{
				$price=$this->_checkPrice($goods);
				
				if(isset($price[3]) && $price[3]==1)
				{
					exit('已使用过竞拍返币了');
				}
				$goods['nowprice']=$price[0];
				$pagetitle=$goods['goods_name'].'定单确认';
				include $this->bidcms_template('order_form');
			}
			else
			{
				sheader(url('user','gain'),1,'产品不存在，请重新下单');
			}
		}
		else
		{
			sheader(url('user','gain'),1,'参数为空，请重新下单');
		}
	}
	//晒单
	function show_action()
	{
        global $get;
		$show_mod=$this->bidcms_model('user_show');
		if($get['deleteid'])
		{
            $container = ['id'=>$get['deleteid']];
			$showlist=$show_mod->where($container)->get_one();
			if($showlist && $show_mod->delete_data('1 '.$container))
			{
				sheader(url('order','show'),1,'删除成功');
			}
			else
			{
				sheader(url('order','show'),1,'未删除成功');
			}
		}
		else
		{
			$showpage=array('isshow'=>1,'current_page'=>intval($get['page']),'page_size'=>10,'url'=>'index.php?con=order&act=show','example'=>2);
			$pagetitle='我拍我秀';
			$showlist=$show_mod->where(array('uid'=>$GLOBALS['userinfo']['uid']))->get_page($showpage);
             $count = $show_mod->where(array('uid'=>$GLOBALS['userinfo']['uid']))->get_count('id');
            $pageinfo = $this->bidcms_parse_page($count,$showpage);
			include $this->bidcms_template('user_show'); 
		}
	}
	//晒单修改
	function showmodify_action()
	{
		$show_mod=$this->bidcms_model('user_show');
		
		if($this->bidcms_submit_check('commit'))
		{
            $updateid=intval($this->post('updateid'));
			$data['title']=trim(strip_tags($_POST['title']));
			$data['updatetime']=time();
			$data['username']=$GLOBALS['session']->get('username');
			
			if($_POST['content'])
			{
				$data['content']=trim($_POST['content']);
			}
			if($updateid)
			{
				if($show_mod->where(['id'=>$updateid,'uid'=>$GLOBALS['userinfo']['uid']])->update_data($data))
				{
					sheader(url('order','show'),1,'晒单修改成功');
				}
				else
				{
					sheader(url('order','show'),10,'晒单未修改成功');
				}
			}
			else
			{
				$data['uid']=$GLOBALS['userinfo']['uid'];
				$data['oid']=intval($_POST['orderid']);
				if($data['oid']>0)
				{
					$orderinfo=$this->bidcms_model('order_base')->fields(array('goods_name','order_type','uid','goods_id','total_fee'))->where(['id'=>$data['oid'],'uid'=>$GLOBALS['userinfo']['uid'],'order_status'=>['lt',4],'order_status'=>['gt',0]])->get_one();
				}
				else
				{
					$orderinfo=array();
				}
				if($orderinfo)
				{

					switch($orderinfo['order_type'])
					{
						case 4:
							$goods_mod=$this->bidcms_model('goods_readsecond');
							$goods_info=$goods_mod->fields(array('goods_id','marketprice','nowprice','thumb','goodluck','lasttime'))->where('goods_id',$orderinfo['goods_id'])->get_one();
							$goods_info['type']='秒杀';
							$goods_info['currentuser']='幸运号:'.$goods_info['goodluck'];
						break;
						case 1:
							$goods_mod=$this->bidcms_model('goods_gift');
							$goods_info=$goods_mod->fields(array('id','thumb','marketprice','needcount','lasttime'))->where('id',$orderinfo['goods_id'])->get_one();
							$goods_info['nowprice']=$goods_info['needcount'];
							$goods_info['type']='积分换购商品';
							$goods_info['currentuser']='';
							$goods_info['goods_id']=$goods_info['id'];
						break;
						default :
							$goods_mod=$this->bidcms_model('goods_complete');
							$goods_info=$goods_mod->where('goods_id',$orderinfo['goods_id'])->fields(array('goods_id','thumb','marketprice','nowprice','currentuser','lasttime'))->get_one();
							$goods_info['type']='竞拍商品';
						break;
					}
					$orderinfo['goods_info']=$goods_info;
					$data['order_info']=serialize($orderinfo);
					$data['goods_name']=$orderinfo['goods_name'];
					if($show_mod->insert_data($data))
					{
						sheader(url('order','show'),10,'晒单添加成功');
					}
					else
					{
						sheader(url('order','show'),10,'晒单未添加成功');
					}
				}
				else
				{
					sheader(url('order','show'),10,'不存在此订单');
				}
			}
			
		}
		else
		{
            $updateid=intval($this->get('updateid'));
			if($updateid) {
				$showlist=$show_mod->where('id',$updateid)->get_one();
				$orderinfo=unserialize($showlist['order_info']);
			} else {
                $showlist = $show_mod->fields;
				$oid=intval($this->get('orderid'));
				$orderinfo=$this->bidcms_model('order_base')->fields(array('goods_name','order_type','uid','goods_id','total_fee'))->where(['id'=>$oid,'uid'=>$GLOBALS['userinfo']['uid'],'order_status'=>['lt',4],'order_status'=>['gt',0]])->get_one();
				if(!$orderinfo)
				{
					sheader(url('order','show'),10,'不存在此订单');
				}
				$uid=$GLOBALS['userinfo']['uid'];
			}
			$pagetitle='我拍我秀';
			include $this->bidcms_template('user_showmodify');
		}
	}
	function confirm_action()
	{
		//得到产品id
		$gid=intval($this->post('goodsid'));
		$order_type=intval($this->post('order_type'));
			
		if($gid>0 && $this->bidcms_submit_check('commit')){
				//收货地址
				$address_mod=$this->bidcms_model('user_address');
				if(!empty($this->post('addressid'))) {
					$adata=$address_mod->where('id',intval($this->post('addressid')))->get_one();
				} else {
                    $username = $this->post('username');
                    $telphone = $this->post('telphone');
                    $address = $this->post('address');
					if(empty($username) || empty($telphone) || empty($address)) {
						sheader(url('user','addressmodify'),1,'请先添加收货地址');
					} else {
						$adata['username'] = $username;
						$adata['telphone'] = $telphone;
						$adata['address']= $address;
						$adata['uid']=$GLOBALS['userinfo']['uid'];
						$address_mod->insert_data($adata);
					}
				}
				
				$orderdata['address']=implode('',$adata);
				
				$orderdata['order_no']=time().$GLOBALS['userinfo']['uid'].rand(100,400);
				$orderdata['uid']=$GLOBALS['userinfo']['uid'];
				$orderdata['updatetime']=time();
				$orderdata['hash']=substr(md52(microtime()),3,10);
				if($order_type==1) {
					//积分商品
					$gift_mod=$this->bidcms_model('goods_gift');
					$gift=$gift_mod->where('id',$gid)->get_one();
					if($gift) {
						$userinfo=$this->bidcms_model('user_base')->where('uid',$GLOBALS['userinfo']['uid'])->get_one();
						//检查库存
						if($gift['giftcount']<1) {
							sheader(url('index','gdetails',array('id'=>$gid)),2,'库存不足');
						}
						//检查用户还有未付款业务
						//if($this->_checkGain($GLOBALS['userinfo']['uid'])) {
						//	sheader(url('user','gain'),2,'你还有未付款的业务');
						//}
						//检查用户积分
						if($userinfo['score']<$gift['needcount']) {
							sheader(url('index','gdetails',array('id'=>$gid)),2,'积分不足');
						}
					
						$orderdata['order_status']=1;
						$orderdata['order_type']=1;
						$orderdata['total_fee']=$gift['needcount'];
						$orderdata['goods_name']=$gift['subject'];
						$orderdata['goods_id']=$gift['id'];
						$orderdata['content']=trim(strip_tags($_POST['content']));
						if($this->bidcms_model('order_base')->insert_data($orderdata)) {
							$gdata['giftcount']=$gift['giftcount']-1;
							$gift_mod->where('id',$gid)->update_data($gdata);
							$udata['score']=$userinfo['score']-$gift['needcount'];
							$this->bidcms_model('user_base')->where('uid',$GLOBALS['userinfo']['uid'])->update_data($udata);
                            $GLOBALS['cache']->update('user'.($GLOBALS['userinfo']['uid']%10).':'.$GLOBALS['userinfo']['uid'],$udata);
							//添加资金操作日志记录代码
							$log_mod=$this->bidcms_model('moneylog');
							$ldata['scoreput']=$gift['needcount'];
							$ldata['get']=0;
							$ldata['put']=0;
							$ldata['money']=$userinfo['money'];
							$ldata['title']='积分兑换'.$gift['subject'].',订单号为'.$orderdata['order_no'];
							$ldata['updatetime']=time();
							$ldata['uid']=$GLOBALS['userinfo']['uid'];
							$ldata['username']=$userinfo['username'];
							$log_mod->insert_data($ldata);
							sheader(url('order','list'),1,'下单成功');
						}
					} else {
						sheader(url('index','gift'),1,'产品不存在，请重新下单');
					}
				} elseif($order_type==2) {
					//秒杀
				} else {
					//竞价商品
					$goods_mod=$this->bidcms_model('goods_complete');
					$goods=$goods_mod->where(['goods_id'=>$gid,'goods_status'=>['lt',3]])->get_one();
					if($goods) {
						$total_fee=$this->_checkPrice($goods,1,0,1);
						
						$orderdata['total_fee']=$total_fee[0];
						$orderdata['order_type']=$total_fee[1];
						if($orderdata['total_fee']==0) {
							$orderdata['order_status']=1;
							$orderdata['paytime']=time();
						}
						
						$orderdata['goods_name']=$goods['goods_name'];
						$orderdata['goods_id']=$goods['goods_id'];
						$orderdata['content']=trim(strip_tags($_POST['content']));
						if($this->bidcms_model('order_base')->insert_data($orderdata)) {
							$goods_mod->where('goods_id',$goods['goods_id'])->update_data(array('goods_status'=>2));
							sheader(url('order','list'),1,'下单成功');
						}
					} else {
						sheader(url('user','gain'),1,'产品不存在，请重新下单');
					}
				}
		}
		else
		{
			sheader(url('user','gain'),1,'参数为空，请重新下单');
		}
	}
	function list_action()
	{
		$type=$this->get('type',0);
        $container['uid'] = $GLOBALS['userinfo']['uid'];
        $ext = '';
		if($type==1)
		{
			$ext='&type=1';
			$container['order_type'] = 1;
		}
		$showpage=array('isshow'=>1,'current_page'=>$this->get('page',0),'page_size'=>20,'url'=>'index.php?con=order&act=list'.$ext,'example'=>2);
		
		$orderlist=$this->bidcms_model('order_base')->where($container)->get_page($showpage);
        $count = $this->bidcms_model('order_base')->where($container)->get_count('id');
		$pagetitle='订单列表-用户中心';
        $pageinfo = $this->bidcms_parse_page($count,$showpage);
		include $this->bidcms_template('user_order');
	}

	function payment_action()
	{
		$orderid=intval($this->get('orderid'));
		if($orderid)
		{
			$order=$this->bidcms_model('order_base')->where(['id'=>$orderid,'order_status'=>0])->get_one();
			if($order)
			{
				$pagetitle=$order['order_no'].'订单付款';
				include $this->bidcms_template('order_pay');
			}
			else
			{
				sheader(url('order','list'),1,'订单不存在');
			}
		}
		else
		{
			sheader(url('order','list'),1,'订单为空，请重新付款');
		}
	}
	//订单付款
	function pay_action()
	{
		$userinfo=$this->bidcms_model('user_base')->where('uid',intval($GLOBALS['userinfo']['uid']))->get_one();
		$orderid=intval($this->get('orderid'));
		$order=$this->bidcms_model('order_base')->where(['id'=>$orderid,'order_status'=>0])->get_one();
		if($order)
		{
			$payment = $this->get('gateway','alipay');
			$orderinfo['service']='create_partner_trade_by_buyer'; //担保
			$orderinfo['subject']=$order['goods_name'].'付款';
			$orderinfo['body']=$order['uid'].'limengqi'.$order['hash'].'limengqi'.$order['goods_name'].'付款';
			$orderinfo['price']=$order['total_fee']; //测试使用0.01,正确为$order['total_fee']
			$orderinfo['order_no']=$order['order_no'];
			$orderinfo['logistics_fee']		= "0.00";				//物流费用，即运费。
			$orderinfo['logistics_type']		= "EXPRESS";			//物流类型，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
			$orderinfo['logistics_payment']	= "SELLER_PAY";			//物流支付方式，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
			$orderinfo['return_url']=SITE_ROOT.'/models/alipay/order_return.php';
			$orderinfo['notify_url']=SITE_ROOT.'/models/alipay/order_notify.php';
			$orderinfo['show_url']=SITE_ROOT;
			switch($payment)
			{
				case 'alipay':
				
					include ROOT_PATH.'/tools/alipay.php';
					$pay_mod=new alipay();
					$pay_mod->init($orderinfo,$userinfo);
					$payurl=$pay_mod->create_url();
					sheader($payurl,2,'正离开'.$GLOBALS['setting']['site_title'].'前往支付宝网关进行支付');
					
				break;
			}
		}
		else
		{
			sheader(url('order','list'),3,'请选择要付款的订单');
		}
	}

	//管理订单
	function manage_action()
	{
		$oid=intval($this->get('orderid'));
		$dotype=trim($this->get('dotype'));
		if($oid)
		{
            $container = ["id"=>$oid,"uid"=>$GLOBALS['userinfo']['uid']];
			$order=$this->bidcms_model('order_base')->where($container)->get_one();
			if($order)
			{
				if($dotype=='cancel')
				{
					if($order['order_status']==0)
					{
						$this->bidcms_model('order_base')->where($container)->update_data(array('order_status'=>4));
						sheader(url('order','list'),3,'订单取消成功');
					}
					else
					{
						sheader(url('order','list'),3,'订单'.$GLOBALS['order_status'][$order['order_status']].'无法操作');
					}
				}
				elseif($dotype=='confirm')
				{
					if($order['order_status']==1 || $order['order_status']==2)
					{
						$this->bidcms_model('order_base')->where($container)->update_data(array('order_status'=>3));
						sheader(url('order','list'),3,'确认收货成功');
					}
					else
					{
						sheader(url('order','list'),3,'订单状态为'.$GLOBALS['order_status'][$order['order_status']]);
					}
				}
				else
				{
					sheader(url('order','list'),3,'未定义操作');
				}
			}
			else
			{
				sheader(url('order','list'),3,'订单不存在,请选择要管理的订单');
			}
		}
		else
		{
			sheader(url('order','list'),3,'请选择要管理的订单');
		}
	}
	//查看订单
	function view_action()
	{
		$id=intval($this->get('orderid'));
		$ajax=intval($this->get('ajax'));
		if(!$id)
		{
			if($ajax)
			{
				exit('<script language="javascript">alert(\'参数为空,请选择要管理的订单\');</script>');
			}
			else
			{
				sheader(url('order','list'),3,'参数为空,请选择要管理的订单');
			}
		}
		if($this->bidcms_submit_check('commit'))
		{
			
			$container=['id'=>$id,'uid'=>$GLOBALS['userinfo']['uid']];
			$data['content']=trim(strip_tags($_POST['content']));
			if($_POST['address'])
			{
				$data['address']=trim(strip_tags($_POST['address']));
			}
			if($this->bidcms_model('order_base')->where($container)->update_data($data))
			{
				
				if($ajax)
				{
					exit('<script language="javascript">alert(\'订单修改成功\');Dialog_close();</script>');
				}
				else
				{
					sheader(url('order','view',array('orderid'=>$id)),3,'订单修改成功');
				}
			}
			else
			{
				
				if($ajax)
				{
					exit('<script language="javascript">alert(\'订单修改成功\');Dialog_close();</script>');
				}
				else
				{
					sheader(url('order','list'),3,'订单修改失败');
				}
			}
		}
		else
		{
				$order=$this->bidcms_model('order_base')->where(['id'=>$id,'uid'=>$GLOBALS['userinfo']['uid']])->get_one();
				//检查是否本人订单
				if($order)
				{
                    $pagetitle='订单 '.$order['order_no'].'详情查看';
					//查看订单
					include $this->bidcms_template('order_view');
				}
				else
				{
					if($ajax)
					{
						exit('<script language="javascript">alert(\'订单不存在,请选择要管理的订单\');</script>');
					}
					else
					{
						sheader(url('order','list'),3,'订单不存在,请选择要管理的订单');
					}
						
				}
		}
		
	}
	//积分购买订单
	function scorebuy_action()
	{
		$id=intval($this->get('id'));
		if($id)
		{
			$gift_mode=$this->bidcms_model('goods_gift');
			$order_type=1;
			//检查订单
			$gift=$gift_mode->where('id',$id)->get_one();
			if($gift)
			{
				$userinfo=$this->bidcms_model('user_base')->where('uid',$GLOBALS['userinfo']['uid'])->get_one();
				//检查库存
				if($gift['giftcount']<1)
				{
					sheader(url('index','gdetails',array('id'=>$id)),2,'库存不足');
				}
				//检查用户还有未付款业务
				//if($this->_checkGain($GLOBALS['userinfo']['uid']))
				//{
				//	sheader(url('user','gain'),2,'你还有未付款的业务');
				//}
				//检查用户积分
				if($userinfo['score']<$gift['needcount'])
				{
					sheader(url('index','gdetails',array('id'=>$id)),2,'积分不足');
				}
				$pagetitle=$gift['subject'].'积分购买,定单确认';
				//得到收货地址
				$address_mod=$this->bidcms_model('user_address');
				$address=$address_mod->where(array('uid'=>$GLOBALS['userinfo']['uid']))->get_page();
				include $this->bidcms_template('scorebuy');
			}
			else
			{
				sheader(url('index','gift'),3,'产品不存在');
			}
		}
		else
		{
			sheader(url('index','gift'),3,'请选择要付款的产品');
		}
		
	}
	//积分充值
	function scorecharge_action()
	{
		$id=intval($this->get('id'));
		if($id)
		{
			//得到收货地址
			$address_mod=$this->bidcms_model('user_address');
			$address=$address_mod->where(array('uid'=>$GLOBALS['userinfo']['uid']))->get_page();
			$gift_mode=$this->bidcms_model('goods_gift');
			$gift=$gift_mode->where('id',$id)->get_one();
			$giftmoney=intval($GLOBALS['setting']['site_scoremoney']?$GLOBALS['setting']['site_scoremoney']:1);
			$cuserinfo=$this->bidcms_model('user_base')->where('uid',intval($GLOBALS['userinfo']['uid']))->get_one();
			$totalfee=($gift['needcount']-$cuserinfo['score'])/$giftmoney;
			if($totalfee>0)
			{
				include $this->bidcms_template('dialog_scorecharge');
			}
			else
			{
				exit('你的积分充足不需要充值');
			}
		}
		else
		{
			exit('参数为空');
		}
	}
	//积分充值支付
	function scorepay_action()
	{
		$gid=intval($this->post('gid'));
		//收货地址
		$address_mod=$this->bidcms_model('user_address');
		if(!empty($_POST['addressid']))
		{
			$adata=$address_mod->where('id',intval($_POST['addressid']))->get_one();
		}
		else
		{
			if(empty($_POST['username']) || empty($_POST['telphone']) || empty($_POST['address'])) {
				sheader(url('user','addressmodify'),1,'请先添加收货地址');
			} else {
				$adata['username']=trim(strip_tags($_POST['username']));
				$adata['telphone']=trim(strip_tags($_POST['telphone']));
				$adata['address']=trim(strip_tags($_POST['address']));
				$adata['uid']=$GLOBALS['userinfo']['uid'];
				$address_mod->insert_data($adata);
			}
		}
		
		$orderaddress=implode('',$adata);
		if($gid>0) {
			if( $GLOBALS['userinfo']['uid']>0) {
				$cuserinfo=$this->bidcms_model('user_base')->where('uid',intval($GLOBALS['userinfo']['uid']))->get_one();
			} else {
				sheader(url('user','login'),2,'请先登录');
			}
			$gift_mode=$this->bidcms_model('goods_gift');
			$gift=$gift_mode->where('id',$gid)->get_one();
			if($gift['needcount']<$cuserinfo['score']) {
				sheader(url('index','gift'),2,'您的积分充足可以直接兑换');
			} else {
				$giftmoney=intval($GLOBALS['setting']['site_scoremoney']?$GLOBALS['setting']['site_scoremoney']:1);
				$totalfee=($gift['needcount']-$cuserinfo['score'])/$giftmoney;
				$payment= $this->get('gateway','alipay');
				$orderinfo['service']='create_partner_trade_by_buyer';
				$orderinfo['subject']='积分兑换充值'.$gift['subject'].'('.$cuserinfo['username'].')';
				$orderinfo['body']=$orderaddress;
				$orderinfo['price']=$totalfee; //测试使用0.01,正确为$charge['nowprice']
				$orderinfo['order_no']=$cuserinfo['hash'].'_'.$cuserinfo['uid'].'_'.$gift['id'].'_'.substr(md5(microtime()),rand(0,10),6);
				$orderinfo['logistics_fee']		= "0.00";				//物流费用，即运费。
				$orderinfo['logistics_type']		= "EXPRESS";			//物流类型，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
				$orderinfo['logistics_payment']	= "SELLER_PAY";			//物流支付方式，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
				$orderinfo['return_url']=SITE_ROOT.'/models/alipay/scorereturn.php';
				$orderinfo['notify_url']=SITE_ROOT.'/models/alipay/scorenotify.php';
				$orderinfo['show_url'] = url('index','gift');
				switch($payment)
				{
					case 'alipay':
					
						include ROOT_PATH.'/tools/alipay.php';
						$pay_mod=new alipay();
						$pay_mod->init($orderinfo,$cuserinfo);
						$payurl=$pay_mod->create_url();
						sheader($payurl,2,'正离开'.$GLOBALS['setting']['site_title'].'前往支付宝网关进行支付');
					break;
				}
			}
		}
		else
		{
			sheader(url('index','gift'),2,'参数错误');
		}
	}
    //返币
    function returnmoney_action(){
      global $cache;
      $id = $this->get('gid',0);
      $uid = $GLOBALS['userinfo']['uid'];
      
      $userinfo = $this->bidcms_model('user_base')->fields('uid,username,money')->where('uid',$uid)->get_one();
      if(empty($userinfo)){
        $this->bidcms_error("未登录");
      }
      $returnlog= $this->bidcms_model('user_returnmoney')->where(["gid"=>$id,"uid"=>$uid])->get_one();
      if($returnlog)
      {
        $this->bidcms_error("已返利");
      }
      $goods=$this->bidcms_model('goods_complete')->fields('backmoney,goods_id,currentuid')->where(["goods_id"=>$id])->get_one();
      if($goods && $uid>0 && $goods['currentuid']!=$uid && $goods['backmoney']>0)
      {
        //返利为0
        if($goods['backmoney']<=0)
        {
          exit("{'datastatus':'backnull'}");
        }
        //判断是否参加过补差兑换了
        $order = $this->bidcms_model('order_base')->where(['uid'=>$uid,'goods_id'=>$id,'order_type'=>2])->get_count();
        if($order>0)
        {
          $this->bidcms_error('已参加补差兑换');
        }
        //计算用户已花费
        $bidlog= $this->bidcms_model('goods_bidlog')->fields('money')->where(['uid'=>$uid,'gid'=>$id])->get_one();
        if($bidlog['money']>0)
        {
          $backmoney=floatval($bidlog['money']*$goods['backmoney'])/100;
          //更新用户记录
		  $rows = $this->bidcms_model('user_base')->where('uid',$uid)->update_add_data('money',$backmoney);
          $cache->update('user'.($uid%10).':'.$uid,array('money'=>floatval($userinfo['money']+$backmoney)));
          if($rows>0) {
            //写入返利
            $money_mod=$this->bidcms_model('user_returnmoney');
            $rdata['gid'] = $id;
            $rdata['uid'] = $uid;
            $rdata['backmoney'] = $goods['backmoney'];
            $rdata['money'] = $bidlog['money'];
            $rdata['resultmoney'] = $backmoney;
            $rdata['updatetime']=time();
            $money_mod->insert_data($rdata);
            
			//添加资金操作日志记录代码
            $log_mod=$this->bidcms_model('moneylog');
            $ldata['get'] = floatval($backmoney);
            $ldata['put'] = 0;
            $ldata['money'] = $userinfo['money'];
            $ldata['title']='竞拍返币';
            $ldata['updatetime']=time();
            $ldata['uid'] = $GLOBALS['userinfo']['uid'];
            $ldata['username'] = $GLOBALS['userinfo']['username'];
            $log_mod->insert_data($ldata);
            $this->bidcms_success(array('datastatus'=>'success','id'=>$id,'backmoney'=>$backmoney));
          } else {
            $this->bidcms_error('返利失败,未更新余额');
          }
        }
        $this->bidcms_error('返利失败');
      } else {
        $this->bidcms_error('商品不存在');
      }
    }
	//判断应付价格
	function _checkPrice($goods,$deletecard=0,$secondbuy=0,$deletescore=0)
	{
		
		if($secondbuy)
		{
			return $goods['nowprice'];
		}
		else
		{
			$ordertotal=$this->bidcms_model('order_base')->where(['goods_id'=>$goods['goods_id'],'uid'=>$GLOBALS['userinfo']['uid']])->get_count('id');
			
			$userinfo=$this->bidcms_model('user_base')->fields(array('usercard','score'))->where('uid',$GLOBALS['userinfo']['uid'])->get_one();
			
			if($ordertotal<1) 
			{
				
				if($goods['currentuid'] == $GLOBALS['userinfo']['uid']) //成功用户下单购买
				{
					$money=$goods['nowprice'];
					
					if($deletescore)
					{
						//竞拍次数
						$buylog_mod=$this->bidcms_model('goods_bidlog');
						$buylog=$buylog_mod->where(['uid'=>$GLOBALS['userinfo']['uid'],'gid'=>$goods['goods_id']])->get_one();
						
						//计算出最后应扣除的积分
						if($buylog['count']>0 && $goods['diffscore']>0 && $userinfo['score']>0 && $buylog['count']*$goods['diffscore']<$userinfo['score'])
						{
							$updatescore=-1*abs($buylog['count']*$goods['diffscore']);
							$this->user->where('uid',$GLOBALS['userinfo']['uid'])->update_data(array('field'=>'score','value'=>$updatescore));
						}
						else
						{
							$this->user->where('uid',$GLOBALS['userinfo']['uid'])->update_data(array('score'=>0));
						}
					}
					$ordertype=0;
				}
				else //一般用户差价购买
				{
					//已参加过返币
					$return_mod=$this->bidcms_model('user_returnmoney');
					$returnlog=$return_mod->where(["gid"=>$goods['goods_id'],"uid"=>$GLOBALS['userinfo']['uid']])->get_one();
					if($returnlog)
					{
						return array($goods['marketprice'],3,0,true);
						$money=$goods['marketprice'];
						$ordertype=3;
					}
					else
					{
						$userputmoney=$this->_checkPutmoney($goods);
						$money=$goods['marketprice']>$userputmoney?abs($goods['marketprice']-$userputmoney):0;
						$ordertype=2;
					}
				}
			} else {
				$money=$goods['marketprice']; //全部用户全价购买
				$ordertype=3;
			}
			$resultmoney=$money-$userinfo['usercard'];
			
			if($deletecard) {
				$this->bidcms_model('user_base')->where('uid',$GLOBALS['userinfo']['uid'])->update_data(array('usercard'=>0));
			}
			$resultmoney=$resultmoney+floatval($goods['yfeemoney']);
			if($resultmoney>0) {
				return array($resultmoney,$ordertype,$userinfo['usercard']);
			} else {
				return array(0,$ordertype,$userinfo['usercard']);
			}
		}
	}
	//判断用户已花费
	function _checkPutmoney($goods)
	{
		$buylog_mod=$this->bidcms_model('goods_bidlog');
		$buylog=$buylog_mod->where(['uid'=>$GLOBALS['userinfo']['uid'],'gid'=>$goods['goods_id']])->get_one();
		$buymoney=!empty($GLOBALS['setting']['site_buymoney'])?floatval($GLOBALS['setting']['site_buymoney']):100;
		return isset($buylog)?($buylog['money']/$buymoney):0;
	}
	//判断积分兑换前是否有成功单子
	function _checkGain($uid)
	{
		$complete_mod=$this->bidcms_model('goods_complete');
		return $complete_mod->where(['currentuid'=>$uid,'goods_status'=>['lt',2]])->get_one();
	}
}